package com.iflytek.demo.slice;

import com.iflytek.demo.ResourceTable;
import com.iflytek.demo.ability.ots.OtsClient;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
/**
 * 讯飞开放平台翻译
 * @author  zhhuang10
 * @date    2021/7/2
 * @version
 */
public class TransSlice extends BaseSlice {

    private TextField textField;
    // EventHandler
    private final EventHandler handler = new EventHandler(EventRunner.getMainEventRunner());
    private TextField textResult;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_trans);
        initView();
    }

    private void initView() {
        textField = (TextField) findComponentById(ResourceTable.Id_textField);
        textResult = (TextField) findComponentById(ResourceTable.Id_text_result);
        final Text translateBtn = (Text) findComponentById(ResourceTable.Id_text_translate);
        translateBtn.setClickedListener(component -> translate());
    }

    private void translate() {
        if (textField.getText().isEmpty()) {
            return;
        }
        OtsClient otsClient = new OtsClient();
        // 设置账号 从讯飞开放平台注册后获取
        otsClient.setAppId("593f8106");
        otsClient.setApiKey("bb613e53ecafcb6d7bee2fca01a3cc37");
        otsClient.setApiSecret("45e92e31278992b6ca13784cd25eab87");
        new Thread(() -> {
            // 开始翻译 包含网络请求 放在子线程
            String result = otsClient.start(textField.getText(), "cn", "en");
            handler.postTask(() -> {
                if (result != null) {
                    textResult.setText(result);
                } else {
                    showToast("网络异常");
                }
            });
        }).start();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
